package com.bj.boot.controller;

import com.bj.boot.bean.Account;
import com.bj.boot.bean.City;
import com.bj.boot.bean.User;
import com.bj.boot.service.AccountService;
import com.bj.boot.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author shkstart
 * @create 2021-09-14 16:48
 */
@Controller
public class IndexController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    AccountService accountService;

    @Autowired
    CityService cityService;

    @ResponseBody
    @GetMapping("/insertCity")
    public Integer insertCity(City city){
        return cityService.insertCity(city);
    }

    @ResponseBody
    @GetMapping("/city")
    public City getCityById(@RequestParam("id") Long id){
        return cityService.getById(id);
    }

    @GetMapping("/acctInsert")
    @ResponseBody
    public Integer insert(@RequestParam("name") String name,
                          @RequestParam("age") Integer age){
        return accountService.addAcct(name,age);
    }

    @GetMapping("/acct")
    @ResponseBody
    public Account getById(@RequestParam("id") Long id){
        return accountService.getAcctById(id);
    }

    @ResponseBody
    @GetMapping("/sql")
    public String queryFromTest(){
        Long aLong = jdbcTemplate.queryForObject("select count(*) from student", Long.class);
        return aLong.toString();
    }

    @GetMapping(value={"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model){
        if(StringUtils.hasLength(user.getUserName())&&StringUtils.hasLength(user.getPassword())){
            session.setAttribute("loginUser",user);
            return "redirect:/main.html";
        }else{
            //model.addAttribute("msg","账号密码错误");//msg在request中
            session.setAttribute("msg","账号密码错误");//msg在session中
            return "login";
        }
    }
    @GetMapping("/main.html")
    public String mainPage(HttpSession session,Model model){
        //Object loginUser = session.getAttribute("loginUser");
        //if(loginUser!=null){
        //    return "main";
        //}else{
        //    model.addAttribute("msg","请重新登录");
        //    return "login";
        //}
        return "main";
    }
}
